import {
  createRouter,
  createWebHashHistory,
  type RouteRecordRaw,
} from "vue-router";
import { getToken } from "@/utils/auth";
import { start, done, configure } from "nprogress";
import "nprogress/nprogress.css";
import { useUserStore } from "@/stores/user";

configure({
  showSpinner: false,
});

// 动态路由
export const asyncRoutes: RouteRecordRaw[] = [
  {
    path: "/home",
    component: () => import("@/views/home/Home.vue"),
    meta: {
      title: "首页",
      icon:'@/assets/images/setup.png',
    },
  },
  {
    path: "/user",
    component: () => import("@/views/user/setUser.vue"),
    meta: {
      title: "用户设置",
      icon:'@/assets/images/setup.png',
      permission: ["0", "1"], // 这个属性的意思是当状态为'0'或'1'时，可以访问此路由；不写这个属性表示这个路由不需要权限
    },
  },
  {
    path: "/partner",
    component: () => import("@/views/partner/setParner.vue"),
    meta: {
      title: "合作商管理",
      icon:'@/assets/images/setup.png',
      permission: ["0", "1"], // 这个属性的意思是当状态为'0'或'1'时，可以访问此路由；不写这个属性表示这个路由不需要权限
    },
  },
  {
    path: "/goods",
    component: () => import("@/views/goods/setGoods.vue"),
    meta: {
      title: "商品大类",
      icon:'@/assets/images/setup.png',
      permission: ["0", "1"], // 这个属性的意思是当状态为'0'或'1'时，可以访问此路由；不写这个属性表示这个路由不需要权限
    },
  },
  {
    path: "/purchaseOrder",
    component: () => import("@/views/purchaseOrder/PurchaseOrder.vue"),
    meta: {
      title: "采购单列表",
      icon:'@/assets/images/setup.png',
      permission: ["0", "1"], // 这个属性的意思是当状态为'0'或'1'时，可以访问此路由；不写这个属性表示这个路由不需要权限
    },
  },

  {
    path: "/bySchool",
    component: () => import("@/views/sumOrder/bySchool.vue"),
    meta: {
      title: "汇总列表/按学校",
      icon:'@/assets/images/setup.png',
      permission: ["0", "1"], // 这个属性的意思是当状态为'0'或'1'时，可以访问此路由；不写这个属性表示这个路由不需要权限
    },
  },
  {
    path: "/byClass",
    component: () => import("@/views/sumOrder/byClass.vue"),
    meta: {
      title: "汇总列表/按大类",
      icon:'@/assets/images/setup.png',
      permission: ["0", "1"], // 这个属性的意思是当状态为'0'或'1'时，可以访问此路由；不写这个属性表示这个路由不需要权限
    },
  },

  {
    path: "/unDelivery",
    component: () => import("@/views/singleOrder/unDelivery.vue"),
    meta: {
      title: "分单列表/未配送",
      icon:'@/assets/images/setup.png',
      permission: ["0", "1"], // 这个属性的意思是当状态为'0'或'1'时，可以访问此路由；不写这个属性表示这个路由不需要权限
    },
  },
  {
    path: "/Delivery",
    component: () => import("@/views/singleOrder/Delivery.vue"),
    meta: {
      title: "分单列表/已配送",
      icon:'@/assets/images/setup.png',
      permission: ["0", "1"], // 这个属性的意思是当状态为'0'或'1'时，可以访问此路由；不写这个属性表示这个路由不需要权限
    },
  },
];

// 固定的路由
export const routes: RouteRecordRaw[] = [
  {
    path: "/login",
    component: () => import("@/views/login/Login.vue"),
    meta: {
      title: "登录",
    },
  },
  // 主路由
  {
    path: "/",
    component: () => import("@/layout/Layout.vue"),
    redirect: "/home",
    name: "root",
    children: [
      // 由上面的asyncRoutes填充
    ],
  },
  {
    path: "/:pathMatch(.*)*",
    name: "NotFound",
    meta: {
      title: "页面未找到",
    },
    component: () => import("@/views/404/NotFound.vue"),
  },
];

const router = createRouter({
  history: createWebHashHistory(import.meta.env.BASE_URL),
  routes: [...routes],
});

// 动态路由是否已设置
let routerSettinged = false;
// 移除动态路由的函数
const removeRouteFns = [];

router.beforeEach(async (to, from) => {
  start();
  document.title = to.meta.title || "绿秀后台管理系统";
  if (getToken()) {
    if (to.path === "/login") {
      return "/";
    } else {
      const userStore = useUserStore();
      if (!routerSettinged) {
        asyncRoutes.filter((item) => {
          if (!item.meta) throw new Error("动态路由的meta属性必须设置");
          const permissionRoutes = asyncRoutes.filter(
            (item) =>
              !item.meta.permission ||
              item.meta.permission.includes(userStore.tznUser.status)
          );
          permissionRoutes.forEach((item) =>
            removeRouteFns.push(router.addRoute("root", item))
          );
          userStore.menuList = permissionRoutes;
        });
        routerSettinged = true;
        return to.fullPath;
      }
    }
  } else {
    // 退出时必然会进入这里，删除动态路由
    removeRouteFns.forEach((fn) => fn());
    routerSettinged = false;
    if (to.path !== "/login") {
      return "/login";
    }
  }
});

router.afterEach(() => {
  done();
});

export default router;
